<template>
  <div class="details-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>套餐详情</span>
      </div>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="套餐名称">
          {{ packageInfo.packageName }}
        </el-descriptions-item>
        <el-descriptions-item label="体检机构">
          {{ packageInfo.hospitalName }}
        </el-descriptions-item>
        <el-descriptions-item label="价格">
          ￥{{ packageInfo.price }}（元）
        </el-descriptions-item>
        <el-descriptions-item label="套餐描述">
          {{ packageInfo.packageDescription }}
        </el-descriptions-item>
        <el-descriptions-item label="体检项目">
          {{ packageInfo.items }}
        </el-descriptions-item>
      </el-descriptions>
      <div class="button-container">
        <el-button type="primary" @click="goBack">返回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getPackage } from "@/api/physicalExamination/package";

export default {
  name: "PackageDetails",
  data() {
    return {
      packageInfo: {
        packageName: '',
        hospitalName: '',
        price: 0,
        packageDescription: '',
        items: ''
      }
    };
  },
  watch: {
    '$route.query.id'(newId, oldId) {
      // 修改处 1：添加路由检查，仅在详情页触发
      if (this.$route.path === '/physicalExamination/package/details' && newId !== oldId) {
        this.resetPackageInfo(); // 重置数据
        this.fetchPackageDetails(); // 重新加载数据
      }
    }
  },
  created() {
    // 修改处 2：在 created 中添加路由检查 -- 解决返回后提示'未找到套餐ID'
    if (this.$route.path === '/physicalExamination/package/details') {
      this.fetchPackageDetails();
    }
  },
  methods: {
    async fetchPackageDetails() {
      try {
        const id = this.$route.query.id;
        if (!id) {
          this.$message.error('未找到套餐ID');
          return;
        }
        const {data} = await getPackage(id);
        this.packageInfo = {
          packageName: data.packageName,
          hospitalName: data.hospitalName,
          price: data.price,
          packageDescription: data.packageDescription,
          items: data.items
        };
      } catch (error) {
        this.$message.error('获取套餐详情失败');
        console.error(error);
      }
    },
    goBack() {
      this.$router.push('/physicalExamination/package'); // 返回套餐列表页
    },
    resetPackageInfo() {
      this.packageInfo = {
        packageName: '',
        hospitalName: '',
        price: 0,
        packageDescription: '',
        items: ''
      };
    }
  }
};
</script>

<style scoped>
.details-container {
  padding: 20px;
}

.box-card {
  max-width: 800px;
  margin: 0 auto;
}

.button-container {
  margin-top: 20px;
  text-align: center;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>
